<?php

/**
 * @package Bike
 * @subpackage Environment
 */

/**
 * Environment handling class
 * @author Chrome
 * @package Bike
 * @subpackage Environment
 */
class Bike_Environment {

	protected $siteName = 'default';
	protected $currentNodeData  = array();

	public function __construct(){
		$request = Bike_Service_Locator::getService('Request');
		$siteName = $request->getServerVar('SERVER_NAME');
		if(null != $siteName ){
			$this->siteName = $siteName;
		}
	}

	public function getSiteName(){
		return $this->siteName;
	}

	protected function identifyDocument($uri = ''){
		$storage = Bike_Service_Locator::getService('SiteTree');
		$nodeData = $storage->getNodeByUri($uri);
		if(empty($nodeData)){
			$nodeData = Bike_Service_Locator::getService('EventsManager')->fireEvent('DOCUMENT_NOT_FOUND');
		}
		if(!empty($nodeData) && $this->checkAcl($nodeData)){
			return $nodeData;
		}else{
			return array();
		}
	}

	public function checkAcl(array $nodeData){
		$request = Bike_Service_Locator::getService('Request');
		if(!empty($nodeData['acl'])){
			$userManager = Bike_Service_Locator::getService('UserManager');
			if(null != $request->getRequestVar('logout')){
				$userManager->logout();
			}
			if($userManager->getCurrentUser() == $userManager->getAnonymous()){
				throw new Bike_Environment_Exception('Access denied', Bike_Environment_Exception::ACCESS_DENIED);
			}
		}
		return true;
	}

	public function handleRequest(){
		$config = Bike_Service_Locator::getService('Config');
		$request = Bike_Service_Locator::getService('Request');
		$nodeData = $this->identifyDocument('/' . $config->getValue(array('sites', $this->siteName)) . $request->getPath());
		$this->currentNodeData = $nodeData;
		if(empty($nodeData)){
			throw new Bike_Environment_Exception('Page not found', Bike_Environment_Exception::PAGE_NOT_FOUND);
		}
		if(empty($nodeData['template_engine'])){
			$parser = Bike_Service_Locator::getService('Parser_bo');
		}else{
			$parser = Bike_Service_Locator::getService('Parser_fe');
		}
		$parser->setTemplate($nodeData['template']);
		return $parser->processTemplate();
	}

	public function getEntityStorage($storageName){
		$config = Bike_Service_Locator::getService('Config');
		$section = $config->getValue(array('entities', $storageName));
		$className = 'Bike_Storage_' . $section['type'];
		$storage = new $className($section['fields']);
		$storage->setStorageName($storageName);
		return $storage;
	}

	public function getCurrentNodeData(){
		return  $this->currentNodeData;
	}
}
